//
//  UIView+xib.swift
//  GRVoice
//
//  Created by tucici on 2021/10/12.
//  Copyright © 2021 国瑞语音. All rights reserved.
//

import Foundation
import UIKit
private var bgHexColorKey = "bgHexColorKey"
private var bgColorViewKey = "bgColorViewKey"
private var bgLayerKey = "bgLayerKey"
private var borderWidthKey = "borderWidthKey"
private var borderColorKey = "borderColorKey"
private var cornarRadiusKey = "cornarRadiusKey"
private var backGroundHexColorKey = "backGroundHexColorKey"
private var borderHexColorKey = "borderHexColorKey"
private var textHexColorKey = "textHexColorKey"
//MARK: - UIView常规方法
extension UIView
{
    @objc func setupUI(){}
    
    @objc func removeAllSubView()
    {
        for view in self.subviews
        {
            view.removeFromSuperview()
        }
    }
}

//MARK: - 关联xib的属性
extension UIView
{
    @IBInspectable var bgHexColor : String{
        set {
            objc_setAssociatedObject(self, &bgHexColorKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
            if newValue == ""{return}
            self.backgroundColor = bgHexColor.color()
        }get{
            return objc_getAssociatedObject(self, &bgHexColorKey) as! String
        }
    }
    @IBInspectable var borderWidth : CGFloat{
        set{
            objc_setAssociatedObject(self, &borderWidthKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
            self.layer.borderWidth = newValue
            self.layer.masksToBounds = true
        }get{
            return objc_getAssociatedObject(self, &borderWidthKey) as? CGFloat ?? 0.0
        }
    }
    @IBInspectable var borderColor:UIColor{
        set{
            self.layer.borderColor = newValue.cgColor
            self.layer.masksToBounds = true
            objc_setAssociatedObject(self, &borderColorKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }get{
            return objc_getAssociatedObject(self, &borderColorKey) as? UIColor ?? UIColor.clear
        }
    }
    
    @IBInspectable var cornerRadius:CGFloat{
        set{
            self.layer.cornerRadius = newValue
            self.layer.masksToBounds = true
            objc_setAssociatedObject(self, &cornarRadiusKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
        }get{
            return objc_getAssociatedObject(self, &cornarRadiusKey) as? CGFloat ?? 0.0
        }
    }
    @IBInspectable var borderHexColor:String{
        set{
            objc_setAssociatedObject(self, &borderColorKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
            if newValue == "" {return}
            self.layer.borderColor = newValue.color().cgColor
        }get{
            return objc_getAssociatedObject(self, &borderColorKey) as? String ?? "#FFFFFF"
        }
    }
    
    @IBInspectable  var textHexColor:String{
        set{
            objc_setAssociatedObject(self, &textHexColorKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
            if self.isKind(of: UIButton.self){
                let btn = self as! UIButton
                btn.setTitleColor(newValue.color(), for: .normal)
            }else if self.isKind(of: UILabel.self){
                let lbl = self as! UILabel
                lbl.textColor = newValue.color()
            }else if self.isKind(of: UITextField.self){
                let input = self as! UITextField
                input.textColor = newValue.color()
            }else if self.isKind(of: UITextView.self){
                let textview = self as! UITextView
                textview.textColor = newValue.color()
            }
        }get{
            return objc_getAssociatedObject(self, &textHexColorKey) as? String ?? "#333333"
        }
    }
    
}


//MARK: - UIView的渐变色背景
extension UIView
{
    /// 渐变色UIView
    private var bgColorView : UIView
    {
        set {
            objc_setAssociatedObject(self, &bgColorViewKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }get{
            return objc_getAssociatedObject(self, &bgColorViewKey) as? UIView ?? UIView()
        }
    }
    
    /// 渐变色Layer
    private var bgLayer : CAGradientLayer
    {
        set {
            objc_setAssociatedObject(self, &bgLayerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        } get{
            return objc_getAssociatedObject(self, &bgLayerKey) as? CAGradientLayer ?? CAGradientLayer()
        }
    }
    
    func gradient(_ colors:[String])
    {
        var array = [UIColor]()
        for color in colors{
            array.append(color.color())
        }
        self.gradient(array, [0.2,1.0], .zero, CGPoint(x: 1, y: 0))
    }
    
    func gradient(_ colors:[String], _ locations:[Float])
    {
        var array = [UIColor]()
        for color in colors{
            array.append(color.color())
        }
        self.gradient(array, locations, .zero, CGPoint(x: 1, y: 0))
    }
    
  @objc func gradient(_ colors:[UIColor], _ locations:[Float], _ startP:CGPoint, _ endP:CGPoint)
    {
        var color_array : [CGColor] = Array()
        for s in colors
        {
            color_array.append(s.cgColor)
        }
        
        var location_array : [NSNumber] = Array()
        for l in locations
        {
            location_array.append(NSNumber(value:l))
        }
        self.bgColorView = UIView()
        self.bgLayer = CAGradientLayer()
        self.bgLayer.colors = color_array
        self.bgLayer.locations = location_array
        self.bgLayer.startPoint = startP
        self.bgLayer.endPoint = endP
        self.setupColors()
    }
    
    private func setupColors()
    {
        self.addSubview(self.bgColorView)
        self.sendSubviewToBack(self.bgColorView)
        self.bgColorView.isUserInteractionEnabled = false
        self.bgColorView.translatesAutoresizingMaskIntoConstraints = false
        
        let top : NSLayoutConstraint = NSLayoutConstraint(item:self.bgColorView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)
        
        let left : NSLayoutConstraint = NSLayoutConstraint(item:self.bgColorView, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0)
        
        let right : NSLayoutConstraint = NSLayoutConstraint(item:self.bgColorView, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0)
        
        let bottom : NSLayoutConstraint = NSLayoutConstraint(item:self.bgColorView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)
        
        self.addConstraints([top,left,right,bottom])
        
        self.layoutIfNeeded()
        self.bgLayer.frame = self.bgColorView.bounds
        self.bgColorView.layer.addSublayer(self.bgLayer)
        
    }
}


//MARK: - 从xib加载文件
extension UIView
{
    
    /// 获取本类的nib
    /// - Returns: UINib
    class func nib() -> UINib
    {
        return UINib(nibName:self.className, bundle: nil)
    }
    
    
    /// 注册cell的时，所需要的id
    /// - Returns: cell的ID
    class func ID() -> String
    {
        return "\(self.className)ID"
    }
    
    /// 以代码加载的xib控件
    /// - Returns: XIB控件
    class func loadFromXIB() -> UIView
    {
        return Bundle.main.loadNibNamed(self.className, owner: nil, options: nil)?.last as! UIView
    }
    
    
    /// 以XIB形式加载xib控件
    /// 这里必须选择 File's Owner. 如果设置的是View 的 Custom Class  为 自定义的类 ，程序将出现问题。
    ///   required init?(coder: NSCoder) {
    ///     super.init(coder: coder)
    ///     self.loadView()
    ///    }
    func loadView()
    {
        let nib : UINib = UINib(nibName: self.className, bundle: nil)
        let view : UIView = nib.instantiate(withOwner: self, options: nil).last as! UIView
        view.frame = self.bounds
        self.addSubview(view)
    }
}



extension UIView {
    func add(_ attr1:NSLayoutConstraint.Attribute,_ r:NSLayoutConstraint.Relation,_ to:UIView?=nil,_ attr2:NSLayoutConstraint.Attribute,_ c:CGFloat)->NSLayoutConstraint{
        return
        NSLayoutConstraint (item: self, attribute:attr1, relatedBy:r, toItem:to, attribute: attr2, multiplier: 1, constant: c)
    }
}
